<?php
/**
 * this is mysql data store class
 * 
 * @author tom.wang<tom.wang.sz@qq.com>
 */
class MysqlOAuthDataStore extends OAuthDataStore {
    public function __construct() {
        //$this->consumer = new OAuthConsumer("key", "secret", NULL);
        //$this->request_token = new OAuthToken("requestkey", "requestsecret", 1);
        //$this->access_token = new OAuthToken("accesskey", "accesssecret", 1);
        //$this->nonce = "nonce";
    }

    public function lookup_consumer($consumer_key) {
		//通過consumer_key查找是否有這個consumer
		//查找到：return new OAuthConsumer(consumer_key, consumer_secret);
		//沒查找到：return null;
        if ($consumer_key == $this->consumer->key) return $this->consumer;
        return NULL;
    }

    public function lookup_token($consumer, $token_type, $token) {
        $token_attrib = $token_type . "_token";
        if ($consumer->key == $this->consumer->key
            && $token == $this->$token_attrib->key) {
            return $this->$token_attrib;
        }
        return NULL;
    }

    public function lookup_nonce($consumer, $token, $nonce, $timestamp) {
        if ($consumer->key == $this->consumer->key
            && (($token && $token->key == $this->request_token->key)
                || ($token && $token->key == $this->access_token->key))
            && $nonce == $this->nonce) {
            return $this->nonce;
        }
        return NULL;
    }

    public function new_request_token($consumer, $callback = null) {
		//通過consumer_key查找是否有這個consumer
		//查找到：生成一個新的request token，并保存到數據庫，然後返回
		//	return new OAuthToken(request_token, request_token_secret);
		//沒查找到：return null;
		
		//request token應該有一個過期時間（一般5分鐘）
        if ($consumer->key == $this->consumer->key) {
            return $this->request_token;
        }
        return NULL;
    }

    public function new_access_token($token, $consumer, $verifier = null) {
		//一個用戶、一個consumer對應一個access token，對應一個request token
		//這裡傳過來的token是驗證后的request token
		
		//通過consumer_key和request token，查找數據庫中是否有該記錄
		//查找到：生成一個新的access token，并保存到數據庫，然後返回
		//	return new OAuthToken(access_token, access_token_secret);
		//沒查找到：return null;
		
		//access token應該有一個過期時間（一般一天）
        if ($consumer->key == $this->consumer->key
            && $token->key == $this->request_token->key) {
            return $this->access_token;
        }
        return NULL;
    }
}
?>